package org.jeecg.modules.monitoring.j_monitoring.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.monitoring.j_monitoring.constantConfig.MonitorStatusEnum;
import org.jeecg.modules.monitoring.j_monitoring.utils.EquipmentUtils;
import org.jeecg.modules.monitoring.j_monitoring.constantConfig.MonitorConstant;
import org.jeecg.modules.monitoring.j_monitoring.entity.*;
import org.jeecg.modules.monitoring.j_monitoring.gatewayData.Virtual;
import org.jeecg.modules.monitoring.j_monitoring.mapper.GatewayWarningMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlVirtualMachineMapper;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlVirtualMachine;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlVirtualMachineService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 虚拟机
 * @Author: xiaoyq
 * @Date: 2023-02-22
 * @Version: V1.0
 */
@Api(tags = "虚拟机")
@RestController
@RequestMapping("/j_monitoring/mGlVirtualMachine")
@Slf4j
public class MGlVirtualMachineController extends JeecgController<MGlVirtualMachine, IMGlVirtualMachineService> {
    @Resource
    private MGlVirtualMachineMapper mGlVirtualMachineMapper;

    @Resource
    private GatewayWarningMapper warningMapper;

    @Resource
    private Virtual virtual;

    /**
     * 分页列表查询
     *
     * @param mGlVirtualMachine
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "虚拟机-分页列表查询")
    @RequiresPermissions("虚拟机:查询")
    @ApiOperation(value = "虚拟机-分页列表查询", notes = "虚拟机-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MGlVirtualMachine mGlVirtualMachine,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Result<Page<MGlVirtualMachine>> result = new Result<>();
        Page<MGlVirtualMachine> pagelist = new Page(pageNo, pageSize);
        QueryWrapper<MGlVirtualMachine> queryWrapper = QueryGenerator.initQueryWrapper(mGlVirtualMachine, req.getParameterMap());
        pagelist = mGlVirtualMachineMapper.getPageList(pagelist, queryWrapper);
        List<MGlVirtualMachine> storageResourcesList = pagelist.getRecords();
        List<String> ipList = new ArrayList<>();
        for (MGlVirtualMachine storageResources : storageResourcesList) {
            if (!storageResources.getIsMonitor()) {
                storageResources.setMonitorStatus(EquipmentUtils.getMonitorStatus(storageResources.getWhetherToMonitor()));
            }
            ipList.add(storageResources.getSystemIp());
        }

        List<GatewayWarning> warningList = warningMapper.getAllGroupIpNormal();

        if (mGlVirtualMachine.getIsMonitor()) {
            //查看ping返回值
            for (MGlVirtualMachine machine : pagelist.getRecords()) {


                RealVirtualItem item = virtual.getItem(machine.getName());
                machine.setMonitorStatus(this.getOpenStatus(warningList, item,machine.getSystemIp()));
                if (item != null) {

                    machine.setAllocationDisk(item.getStorageMount().stripTrailingZeros() + "GB" );
                    machine.setAllocationMem(item.getMemeryCount().stripTrailingZeros() + "G");
                    if(item.getCpuKernelNum() > 0 && item.getCpuCount().compareTo(BigDecimal.ZERO) > 0) {
                        machine.setCpu(
                                item.getCpuKernelNum().toString() + "核" + item.getCpuCount().divide(new BigDecimal(item.getCpuKernelNum()),BigDecimal.ROUND_CEILING).stripTrailingZeros() + "GHz");
                    }


                    machine.setOpenStatus(item.getStatus());
                }


            }
        }


        result.setCode(200);
        result.setSuccess(true);
        result.setResult(pagelist);
        return result;
    }

    private String getOpenStatus(List<GatewayWarning> warningList, RealVirtualItem item, String ip) {
        //3 离线 2告警 1正常
        if (item == null) {
            return MonitorStatusEnum.offline.getKey();
        }


        if ("1".equals(item.getStatus())) {

            for (GatewayWarning warning :warningList){
                if (ip.equals(warning.getIp())){
                    return  MonitorStatusEnum.warning.getKey();
                }
            }
            return MonitorStatusEnum.online.getKey();
        }

        return MonitorStatusEnum.offline.getKey();
    }

    /**
     * 设备地图查询
     */
    //@AutoLog(value = "虚拟机-设备地图查询")
    @ApiOperation(value = "虚拟机-设备地图查询", notes = "虚拟机-设备地图查询")
    @GetMapping(value = "/getDeviceMap")
    @RequiresPermissions("虚拟机:查询")
    public Result<?> getDeviceMap(
            @RequestParam(name = "id", required = true) String id,
            HttpServletRequest req) {
        MGlVirtualMachine entity = this.service.getById(id);
        JSONArray nodes = new JSONArray();
        JSONArray edges = new JSONArray();
        JSONObject result = new JSONObject();
        result.put("nodes", nodes);
        result.put("edges", edges);
        if (entity == null) {
            return Result.OK(result);
        }

        JSONObject child, edge, vNode;

        int startX = 0, startY = 0;
        vNode = this.service.getDeviceMapById(nodes, edges, startX, startY, id);
        startX = 0;
        startY = 0;
        if (StringUtils.isNotBlank(entity.getAssociatedApplication())) {
            String[] apps = entity.getAssociatedApplication().split(",");
            for (int i = 0; i < apps.length; i++) {
                child = new JSONObject();
                child.put("category", MonitorConstant.Application);
                child.put("id", "_APP_ID_" + apps[i]);
                child.put("name", apps[i]);
                child.put("x", startX + MonitorConstant.StepX * 0);
                child.put("y", startY);

                nodes.add(child);

                edge = new JSONObject();
                edge.put("source", "_APP_ID_" + apps[i]);
                edge.put("target", entity.getId());
                edges.add(edge);

                startY = startY + MonitorConstant.StepY;
            }
        }


        return Result.OK(result);
    }

    /**
     * 设备地图查询
     */
    //@AutoLog(value = "虚拟机-设备地图查询")
    @ApiOperation(value = "虚拟机-设备地图查询", notes = "虚拟机-设备地图查询")
    @GetMapping(value = "/getDeviceTree")
    @RequiresPermissions("虚拟机:查询")
    public Result<?> getDeviceTree(
            @RequestParam(name = "id", required = true) String id,
            HttpServletRequest req) {
        JSONObject result = new JSONObject();
        MGlVirtualMachine entity = this.service.getById(id);
        if (entity == null) {
            return Result.ok(result);
        }
        result.put("type", "应用");
        result.put("id", "");
        result.put("name", entity.getAssociatedApplication());
        JSONObject child;

        child = this.service.getDeviceTreeById(id);
        JSONArray children = new JSONArray();
        children.add(child);
        result.put("children", children);
        return Result.OK(result);
    }

    /**
     * 添加
     *
     * @param mGlVirtualMachine
     * @return
     */
    @AutoLog(value = "虚拟机-添加")
    @ApiOperation(value = "虚拟机-添加", notes = "虚拟机-添加")
    @RequiresPermissions("虚拟机:添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MGlVirtualMachine mGlVirtualMachine) {
        service.save(mGlVirtualMachine);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mGlVirtualMachine
     * @return
     */
    @AutoLog(value = "虚拟机-编辑")
    @ApiOperation(value = "虚拟机-编辑", notes = "虚拟机-编辑")
    @RequiresPermissions("虚拟机:编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MGlVirtualMachine mGlVirtualMachine) {
        service.updateById(mGlVirtualMachine);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "虚拟机-通过id删除")
    @ApiOperation(value = "虚拟机-通过id删除", notes = "虚拟机-通过id删除")
    @RequiresPermissions("虚拟机:删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        service.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "虚拟机-批量删除")
    @ApiOperation(value = "虚拟机-批量删除", notes = "虚拟机-批量删除")
    @RequiresPermissions("虚拟机:批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.service.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 监控
     *
     * @return
     */
    @AutoLog(value = "虚拟机-添加监控")
    @ApiOperation(value = "虚拟机-添加监控", notes = "虚拟机-添加监控")
    @RequiresPermissions("虚拟机:监控")
    @RequestMapping(value = "/monitor", method = {RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> monitor(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if (idList.size() == 0) {
            return Result.error("数据为空!");
        }
        UpdateWrapper<MGlVirtualMachine> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<MGlVirtualMachine> lambdaUpdateWrapper = updateWrapper.lambda();
        idList.forEach(item -> lambdaUpdateWrapper.or(qr -> qr.eq(MGlVirtualMachine::getId, item)));
        lambdaUpdateWrapper.set(MGlVirtualMachine::getWhetherToMonitor, "1");
        service.update(updateWrapper);
        return Result.OK("监控添加成功!");
    }

    /**
     * 取消监控
     *
     * @return
     */
    @AutoLog(value = "虚拟机-取消监控")
    @ApiOperation(value = "虚拟机-取消监控", notes = "虚拟机-取消监控")
    @RequiresPermissions("虚拟机:取消监控")
    @RequestMapping(value = "/unmonitor", method = {RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> unmonitor(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if (idList.size() == 0) {
            return Result.error("数据为空!");
        }
        UpdateWrapper<MGlVirtualMachine> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<MGlVirtualMachine> lambdaUpdateWrapper = updateWrapper.lambda();
        idList.forEach(item -> lambdaUpdateWrapper.or(qr -> qr.eq(MGlVirtualMachine::getId, item)));
        lambdaUpdateWrapper.set(MGlVirtualMachine::getWhetherToMonitor, "0");
        service.update(updateWrapper);
        return Result.OK("监控取消成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "虚拟机-通过id查询")
    @ApiOperation(value = "虚拟机-通过id查询", notes = "虚拟机-通过id查询")
    @GetMapping(value = "/queryById")
    @RequiresPermissions("虚拟机:查询")
    public Result<MGlVirtualMachine> queryById(@RequestParam(name = "id", required = true) String id) {
        MGlVirtualMachine mGlVirtualMachine = service.getById(id);
        if (mGlVirtualMachine == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mGlVirtualMachine);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mGlVirtualMachine
     */
    @RequiresPermissions("虚拟机:导出")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
    @ApiOperation(value = "虚拟机-导出", notes = "虚拟机-导出")
    public ModelAndView exportXls(HttpServletRequest request, MGlVirtualMachine mGlVirtualMachine) {
        return super.exportXls(request, mGlVirtualMachine, MGlVirtualMachine.class, "虚拟机");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("虚拟机:导入")
    @ApiOperation(value = "虚拟机-导入", notes = "虚拟机-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MGlVirtualMachine.class);
    }

    @ApiOperation(value = "虚拟机-导入", notes = "虚拟机-导入")
    @RequestMapping(value = "/importNew", method = RequestMethod.POST)
    @RequiresPermissions("虚拟机:导入")
    public Result<?> importNew(HttpServletRequest request, HttpServletResponse response) {

        Map<String, String[]> reqMap = request.getParameterMap();
        String ip = reqMap.get("ip") == null ? "10.57" : reqMap.get("ip")[0];

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MGlVirtualMachine> list = ExcelImportUtil.importExcel(file.getInputStream(), MGlVirtualMachine.class, params);
                if (list.size() == 0) {
                    return Result.error("文件导入失败:文件内容为空");
                }

                list = service.dealImportList(list, ip);

                beforeImportExcel(list);
                service.deleteAll();
                long start = System.currentTimeMillis();
                service.saveBatch(list);
                afterImportExcel(list);

//                service.addNumberLog(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    protected void beforeImportExcel(List<MGlVirtualMachine> list) {
        list.forEach(item -> {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(item.getPersonLiable())) {
                item.setPersonLiable(item.getPersonLiable().trim());
            }
        });
    }

    @Override
    protected void afterImportExcel(List<MGlVirtualMachine> list) {
        UpdateWrapper<MGlVirtualMachine> updateWrapper = new UpdateWrapper<>();

        updateWrapper.clear();
        updateWrapper.lambda().isNull(MGlVirtualMachine::getPersonLiableId);
        updateWrapper.setSql("person_liable_id=(select id from sys_user where person_liable=realname LIMIT 1)");
        this.service.update(updateWrapper);
    }
}
